package com.neusoft.elmboot.filter;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.neusoft.elmboot.exception.UnLoginException;
import com.neusoft.elmboot.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT的拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {
    private static final String AUTH_HEADER = "elm-token";
    private static final String TOKEN_PREFIX = "";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Token
        String token = request.getHeader(AUTH_HEADER);
        System.out.println("-------1.进入了JwtInterceptor拦截器！");
        // 校验Token
        if (token == null || !token.startsWith(TOKEN_PREFIX)) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new UnLoginException("您未登录！");
//            return false; // 拦截请求
        }

        try {
            // 去掉Token前缀
            token = token.replace(TOKEN_PREFIX, "");

            // 解析Token并验证
            String username = JWTUtil.getUsernameFromToken(token);
            if (!JWTUtil.validateToken(token)) {
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                throw new UnLoginException("Token不合法！");
//                return false; // 拦截请求
            }

            // 在请求中添加用户名信息
            request.setAttribute("username", username);

        } catch (Exception e) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            if (e instanceof JWTVerificationException) {
                throw new UnLoginException("Token校验失败！");
            } else if (e instanceof UnLoginException) {
                throw e;
            }
            throw e;
//            return false; // 拦截请求
        }

        return true; // 放行请求
    }
}